<template>
  <div class="container">
    <div class="topSelectBox">
      <div
        :class="['selectItem', { active: selectActive == item.id }]"
        @click="selectListItem(item)"
        v-for="item in selectList"
        :key="item.id"
      >
        {{ item.name }}
      </div>
    </div>

    <div id="anchor - 0" class="riskLevelManage">
      <div class="boxTitle">风险级别管理</div>
      <el-button type="primary" class="addBtn" @click="editItem(1, null)"
        >+ 添加</el-button
      >
      <div class="table">
        <el-table
          :header-cell-style="{
            'background-color': '#F5F6F7',
            color: '#313235',
          }"
          :data="tableData1"
          border
          style="width: 100%"
        >
          <el-table-column prop="name" label="标签" width="180">
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间">
          </el-table-column>
          <el-table-column
            align="center"
            prop="address"
            label="操作"
            width="180"
          >
            <template slot-scope="scope">
              <div class="btnBox">
                <div class="editBtn" @click="editItem(1, scope.row)">编辑</div>
                <div class="editBtn delBtn" @click="deleteItem(1, scope.row)">
                  删除
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div id="anchor - 1" class="riskLevelManage">
      <div class="boxTitle">作业方式管理</div>
      <el-button type="primary" class="addBtn" @click="editItem(2, null)"
        >+ 添加</el-button
      >
      <div class="table">
        <el-table
          :header-cell-style="{
            'background-color': '#F5F6F7',
            color: '#313235',
          }"
          :data="tableData2"
          border
          style="width: 100%"
        >
          <el-table-column prop="name" label="标签" width="180">
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间">
          </el-table-column>
          <el-table-column
            align="center"
            prop="address"
            label="操作"
            width="180"
          >
            <template slot-scope="scope">
              <div class="btnBox">
                <div class="editBtn" @click="editItem(2, scope.row)">编辑</div>
                <div class="editBtn delBtn" @click="deleteItem(2, scope.row)">
                  删除
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div id="anchor - 2" class="riskLevelManage">
      <div class="boxTitle">风险辨识管理</div>
      <el-button type="primary" class="addBtn" @click="editItem(3, null)"
        >+ 添加</el-button
      >
      <div class="table">
        <el-table
          :header-cell-style="{
            'background-color': '#F5F6F7',
            color: '#313235',
          }"
          :data="tableData3"
          border
          style="width: 100%"
        >
          <el-table-column prop="name" label="标签" width="180">
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间">
          </el-table-column>
          <el-table-column
            align="center"
            prop="address"
            label="操作"
            width="180"
          >
            <template slot-scope="scope">
              <div class="btnBox">
                <div class="editBtn" @click="editItem(3, scope.row)">编辑</div>
                <div class="editBtn delBtn" @click="deleteItem(3, scope.row)">
                  删除
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div id="anchor - 3" class="riskLevelManage">
      <div class="boxTitle">安全措施管理</div>
      <el-button type="primary" class="addBtn" @click="editItem(4, null)"
        >+ 添加</el-button
      >
      <div class="table">
        <el-table
          :header-cell-style="{
            'background-color': '#F5F6F7',
            color: '#313235',
          }"
          :data="tableData4"
          border
          style="width: 100%"
        >
          <el-table-column prop="name" label="标签"> </el-table-column>
          <el-table-column prop="createTime" label="创建时间">
          </el-table-column>
          <el-table-column
            align="center"
            prop="address"
            label="操作"
            width="180"
          >
            <template slot-scope="scope">
              <div class="btnBox">
                <div class="editBtn" @click="editItem(4, scope.row)">编辑</div>
                <div class="editBtn delBtn" @click="deleteItem(4, scope.row)">
                  删除
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div id="anchor - 4" class="riskLevelManage">
      <div class="boxTitle">分析项目管理</div>
      <el-button type="primary" class="addBtn" @click="editItem(5, null)"
        >+ 添加</el-button
      >
      <div class="table">
        <el-table
          :header-cell-style="{
            'background-color': '#F5F6F7',
            color: '#313235',
          }"
          :data="tableData5"
          border
          style="width: 100%"
        >
          <el-table-column prop="name" label="分析项目"> </el-table-column>
          <el-table-column prop="gasMolecularFormula" label="气体分子式">
          </el-table-column>
          <el-table-column prop="valueType" label="值类型"> </el-table-column>
          <el-table-column prop="comparisonMethod" label="比较方式">
          </el-table-column>
          <el-table-column prop="valueRange" label="取值范围">
          </el-table-column>
          <el-table-column prop="unit" label="单位"> </el-table-column>

          <el-table-column prop="createTime" label="创建时间">
          </el-table-column>
          <el-table-column
            align="center"
            prop="address"
            label="操作"
            width="180"
          >
            <template slot-scope="scope">
              <div class="btnBox">
                <div class="editBtn" @click="editItem(5, scope.row)">编辑</div>
                <div class="editBtn delBtn" @click="deleteItem(5, scope.row)">
                  删除
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div id="anchor - 5" class="riskLevelManage">
      <div class="boxTitle">作业时长设置</div>
      <el-button type="primary" class="addBtn" @click="editItem(6, null)"
        >+ 添加</el-button
      >
      <div class="table">
        <el-table
          :header-cell-style="{
            'background-color': '#F5F6F7',
            color: '#313235',
          }"
          :data="tableData6"
          border
          style="width: 100%"
        >
          <el-table-column prop="ticketTypeName" label="作业票类型名称">
          </el-table-column>
          <el-table-column prop="riskLevelName" label="作业级别">
          </el-table-column>
          <el-table-column prop="duration" label="时长"> </el-table-column>
          <el-table-column prop="unit" label="单位"> </el-table-column>
          <el-table-column prop="createTime" label="创建时间">
          </el-table-column>

          <el-table-column
            align="center"
            prop="address"
            label="操作"
            width="180"
          >
            <template slot-scope="scope">
              <div class="btnBox">
                <div class="editBtn" @click="editItem(6, scope.row)">编辑</div>
                <div class="editBtn delBtn" @click="deleteItem(6, scope.row)">
                  删除
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div id="anchor - 6" class="riskLevelManage">
      <div class="boxTitle">中断时长设置</div>
      <el-button type="primary" class="addBtn" @click="editItem(7, null)"
        >+ 添加</el-button
      >
      <div class="table">
        <el-table
          :header-cell-style="{
            'background-color': '#F5F6F7',
            color: '#313235',
          }"
          :data="tableData7"
          border
          style="width: 100%"
        >
          <el-table-column prop="ticketTypeName" label="作业票类型名称">
          </el-table-column>
          <el-table-column prop="riskLevelName" label="作业级别">
          </el-table-column>
          <el-table-column prop="duration" label="时长"> </el-table-column>
          <el-table-column prop="unit" label="单位"> 分钟</el-table-column>
          <el-table-column prop="createTime" label="创建时间">
          </el-table-column>

          <el-table-column
            align="center"
            prop="address"
            label="操作"
            width="180"
          >
            <template slot-scope="scope">
              <div class="btnBox">
                <div class="editBtn" @click="editItem(7, scope.row)">编辑</div>
                <div class="editBtn delBtn" @click="deleteItem(7, scope.row)">
                  删除
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div id="anchor - 7" class="riskLevelManage">
      <div class="boxTitle">审批人设置</div>
      <el-button type="primary" class="addBtn" @click="editItem(8, null)"
        >+ 添加</el-button
      >
      <div class="table">
        <el-table
          :header-cell-style="{
            'background-color': '#F5F6F7',
            color: '#313235',
          }"
          :data="tableData8"
          border
          style="width: 100%"
        >
          <el-table-column prop="name" label="标签" width="180">
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间">
          </el-table-column>
          <el-table-column
            align="center"
            prop="address"
            label="操作"
            width="180"
          >
            <template slot-scope="scope">
              <div class="btnBox">
                <!-- <div class="editBtn" @click="editItem(3, scope.row)">编辑</div> -->
                <div class="editBtn delBtn" @click="deleteItem(8, scope.row)">
                  删除
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="sideBar">
      <div
        class="sideBarItem"
        v-for="(item, index) in sideBarList"
        :key="index"
        :class="{ active: activeIndex === index }"
        @click="scrollToAnchor(index)"
      >
        {{ item.title }}
        <div class="bottomTia"></div>
      </div>
    </div>

    <addRiskLevel
      @close="addDialog1 = false"
      :addDialog.sync="addDialog1"
      :workId.sync="workId"
      ref="addRiskLevel"
    ></addRiskLevel>
    <addWorkModel
      @close="addDialog2 = false"
      :addDialog.sync="addDialog2"
      :workId.sync="workId"
      ref="addWorkModel"
    ></addWorkModel>
    <addRiskIdentify
      @close="addDialog3 = false"
      :addDialog.sync="addDialog3"
      :workId.sync="workId"
      ref="addRiskIdentify"
    ></addRiskIdentify>

    <addSafeMeasure
      @close="addDialog4 = false"
      :addDialog.sync="addDialog4"
      :workId.sync="workId"
      ref="addSafeMeasure"
    ></addSafeMeasure>

    <addAnalysis
      @close="addDialog5 = false"
      @update-form="handleFormUpdate"
      :addDialog.sync="addDialog5"
      :workId.sync="workId"
      ref="addAnalysis"
    ></addAnalysis>

    <addWorkDuration
      @close="addDialog6 = false"
      :addDialog.sync="addDialog6"
      :workId.sync="workId"
      ref="addWorkDuration"
    ></addWorkDuration>

    <addWorkInterrupt
      @close="addDialog7 = false"
      :addDialog.sync="addDialog7"
      :workId.sync="workId"
      ref="addWorkInterrupt"
    ></addWorkInterrupt>

    <addApprover
      @close="addDialog8 = false"
      :addDialog.sync="addDialog8"
      :workId.sync="workId"
      ref="addApprover"
    ></addApprover>
  </div>
</template>

<script>
import {
  workTypeApi,
  riskLevelListApi,
  deleteRiskLevelApi,
  workModeListApi,
  deleteWorkModeApi,
  riskIdentificationListApi,
  deleteRiskIdentificationApi,
  securityMeasureListApi,
  deleteSecurityMeasureApi,
  analysisItemListApi,
  deleteAnalysisItemApi,
  workDurationListApi,
  deleteWorkDurationApi,
  workInterruptionDurationListApi,
  deleteWorkInterruptionDurationApi,
  approverListApi,
  deleteApproverApi,
} from "@/api/workConfiguration";
import addRiskLevel from "./components/addRiskLevel.vue";
import addWorkModel from "./components/addWorkModel.vue";
import addRiskIdentify from "./components/addRiskIdentify.vue";
import addSafeMeasure from "./components/addSafeMeasure.vue";
import addAnalysis from "./components/addAnalysis.vue";
import addWorkDuration from "./components/addWorkDuration.vue";
import addWorkInterrupt from "./components/addWorkInterrupt.vue";
import addApprover from "./components/addApprover.vue";
export default {
  name: "",
  props: {},
  components: {
    addRiskLevel,
    addWorkModel,
    addRiskIdentify,
    addSafeMeasure,
    addAnalysis,
    addWorkDuration,
    addWorkInterrupt,
    addApprover,
  },
  data() {
    return {
      selectList: [],
      selectActive: 0,
      tableData1: [],
      tableData2: [],
      tableData3: [],
      tableData4: [],
      tableData5: [],
      tableData6: [],
      tableData7: [],
      tableData8: [],
      activeIndex: 0, // 当前激活的锚点索引
      observer: null, // IntersectionObserver实例
      scrollTimeout: null, // 滚动防抖定时器
      sideBarList: [
        { title: "风险级别管理" },
        { title: "作业方式管理" },
        { title: "风险辨识管理" },
        { title: "安全措施管理" },
        { title: "分析项目管理" },
        { title: "作业时长设置" },
        { title: "中断时长设置" },
        { title: "审批人设置" },
      ],
      showDialog: null,
      isDialog: null,
      workId: "0",
      addDialog1: false,
      addDialog2: false,
      addDialog3: false,
      addDialog4: false,
      addDialog5: false,
      addDialog6: false,
      addDialog7: false,
      addDialog8: false,
    };
  },
  created() {
    this.workTypeApiGet();
  },
  methods: {
    async workTypeApiGet() {
      const res = await workTypeApi();
      this.selectList = res.data;
      this.selectActive = res.data[0].id;
      this.workId = res.data[0].code;
      this.riskLevelListApiGet();
      this.workModeListApiGet();
      this.riskIdentificationListApiGet();
      this.securityMeasureListApiGet();
      this.analysisItemListApiGet();
      this.workDurationListApiGet();
      this.workInterruptionDurationListApiGet();
      this.approverListApiGet();
    },
    async selectListItem(item) {
      this.selectActive = item.id;
      this.workId = item.code;
      this.riskLevelListApiGet();
      this.workModeListApiGet();
      this.riskIdentificationListApiGet();
      this.securityMeasureListApiGet();
      this.analysisItemListApiGet();
      this.workDurationListApiGet();
      this.workInterruptionDurationListApiGet();
      this.approverListApiGet();
    },
    editItem(isDialog, row) {
      if (isDialog == 1) {
        this.addDialog1 = true;
        if (row) {
          this.$refs.addRiskLevel.form = row;
        }
      } else if (isDialog == 2) {
        this.addDialog2 = true;
        if (row) {
          this.$refs.addWorkModel.form = row;
        }
      } else if (isDialog == 3) {
        this.addDialog3 = true;
        if (row) {
          this.$refs.addRiskIdentify.form = row;
        }
      } else if (isDialog == 4) {
        this.addDialog4 = true;
        if (row) {
          this.$refs.addSafeMeasure.form = row;
        }
      } else if (isDialog == 5) {
        this.addDialog5 = true;
        if (row) {
          this.$refs.addAnalysis.form = row;
          if (row.valueType == "区间") {
            const parts = row.valueRange.split("-");
            this.$refs.addAnalysis.$set(
              this.$refs.addAnalysis.form,
              "valueRange1",
              parts[0]
            );
            this.$refs.addAnalysis.$set(
              this.$refs.addAnalysis.form,
              "valueRange2",
              parts[1]
            );
          }
        }
      } else if (isDialog == 6) {
        this.addDialog6 = true;
        this.$refs.addWorkDuration.riskLevelListApiGet();
        if (row) {
          this.$refs.addWorkDuration.form = row;
        }
      } else if (isDialog == 7) {
        this.addDialog7 = true;
        this.$refs.addWorkInterrupt.riskLevelListApiGet();
        if (row) {
          this.$refs.addWorkInterrupt.form = row;
        }
      } else if (isDialog == 8) {
        this.addDialog8 = true;
        this.$refs.addApprover.userListApiGet();
        if (row) {
          this.$refs.addApprover.form = row;
        }
      }
    },
    deleteItem(isDialog, row) {
      this.$confirm(`此操作将永久删除该标签, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          if (isDialog == 1) {
            const res = await deleteRiskLevelApi({ id: row.id });
            if (res.data) {
              this.riskLevelListApiGet();
            }
          } else if (isDialog == 2) {
            const res = await deleteWorkModeApi({ id: row.id });
            if (res.data) {
              this.workModeListApiGet();
            }
          } else if (isDialog == 3) {
            const res = await deleteRiskIdentificationApi({ id: row.id });
            if (res.data) {
              this.riskIdentificationListApiGet();
            }
          } else if (isDialog == 4) {
            const res = await deleteSecurityMeasureApi({ id: row.id });
            if (res.data) {
              this.securityMeasureListApiGet();
            }
          } else if (isDialog == 5) {
            const res = await deleteAnalysisItemApi({ id: row.id });
            if (res.data) {
              this.analysisItemListApiGet();
            }
          } else if (isDialog == 6) {
            const res = await deleteWorkDurationApi({ id: row.id });
            if (res.data) {
              this.workDurationListApiGet();
            }
          } else if (isDialog == 7) {
            const res = await deleteWorkInterruptionDurationApi({ id: row.id });
            if (res.data) {
              this.workInterruptionDurationListApiGet();
            }
          } else if (isDialog == 8) {
            const res = await deleteApproverApi({ id: row.id });
            if (res.data) {
              this.approverListApiGet();
            }
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 点击侧边栏跳转到对应锚点
    scrollToAnchor(index) {
      const element = document.getElementById(`anchor - ${index}`);
      // console.log(element);
      if (element) {
        // 平滑滚动到锚点
        element.scrollIntoView({
          behavior: "smooth",
          block: "start",
        });
        // 更新当前激活索引
        this.activeIndex = index;
      }
    },
    // 设置IntersectionObserver监听锚点
    setupIntersectionObserver() {
      const options = {
        root: null,
        rootMargin: "-20% 0px -50% 0px", // 上下观察区域各缩小
        threshold: 0.5, // 当50%进入视口时触发
      };

      this.observer = new IntersectionObserver((entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            const id = entry.target.id;
            const index = parseInt(id.split("-")[1]);
            this.activeIndex = index;
          }
        });
      }, options);

      // 监听所有锚点区域
      this.sideBarList.forEach((_, index) => {
        const element = document.getElementById(`anchor - ${index}`);
        if (element) {
          this.observer.observe(element);
        }
      });
    },
    handleFormUpdate(updatedForm) {
      // 更新父组件中的数据
      this.row = updatedForm;
    },
    async riskLevelListApiGet() {
      const res = await riskLevelListApi({
        ticketTypeCode: this.workId,
      });
      this.tableData1 = res.data;
    },
    async workModeListApiGet() {
      const res = await workModeListApi({
        ticketTypeCode: this.workId,
      });
      this.tableData2 = res.data;
    },
    async riskIdentificationListApiGet() {
      const res = await riskIdentificationListApi({
        ticketTypeCode: this.workId,
      });
      this.tableData3 = res.data;
    },
    async securityMeasureListApiGet() {
      const res = await securityMeasureListApi({
        ticketTypeCode: this.workId,
      });
      this.tableData4 = res.data;
    },
    async analysisItemListApiGet() {
      const res = await analysisItemListApi({
        ticketTypeCode: this.workId,
      });
      this.tableData5 = res.data;
    },
    async workDurationListApiGet() {
      const res = await workDurationListApi({
        ticketTypeCode: this.workId,
      });
      this.tableData6 = res.data;
    },
    async workInterruptionDurationListApiGet() {
      const res = await workInterruptionDurationListApi({
        ticketTypeCode: this.workId,
      });
      this.tableData7 = res.data;
    },
    async approverListApiGet() {
      const res = await approverListApi({
        ticketTypeCode: this.workId,
      });
      this.tableData8 = res.data;
    },
  },

  mounted() {
    this.setupIntersectionObserver();
  },
  beforeDestroy() {
    if (this.observer) this.observer.disconnect();
    clearTimeout(this.scrollTimeout);
  },
  watch: {},
  computed: {},
  filters: {},
};
</script>

<style scoped lang="scss">
.container {
  background-color: #fff;
  padding: 20px;
  padding-right: 100px;
  .topSelectBox {
    display: flex;
    margin-bottom: 20px;
    .selectItem {
      width: 160px;
      height: 40px;
      background: #fff;
      border: 1px solid #dbdee5;
      line-height: 40px;
      text-align: center;
      color: #525459;
      cursor: pointer;
      margin-right: -1px; /* 关键：右移1px，覆盖相邻边框 */
      border-radius: 0 !important;
      &:first-child {
        border-top-left-radius: 4px !important;
        border-bottom-left-radius: 4px !important;
      }
      &:last-child {
        border-top-right-radius: 4px !important;
        border-bottom-right-radius: 4px !important;
      }
    }
    .active {
      background: #f0f7ff;
      border: 1px solid #96bcff;
      color: #0077ff;
      z-index: 1; /* 提高层级，避免被相邻元素覆盖 */
    }
  }
  .riskLevelManage {
    margin-bottom: 20px;
    scroll-margin-top: 80px; /* 根据实际导航栏高度调整 */
    .boxTitle {
      font-weight: bold;
      font-size: 18px;
      color: #313235;
    }
    .boxTitle::before {
      content: "";
      display: inline-block;
      width: 4px;
      height: 16px;
      background: #0077ff;
      margin-right: 10px;
    }
    .addBtn {
      width: 72px;
      height: 36px;
      background: #0077ff;
      border-radius: 4px 4px 4px 4px;
      text-align: center;
      line-height: 36px;
      color: #fff;
      margin: 20px 0 10px 0;
      padding: 0 !important;
    }
    .table {
      .btnBox {
        color: #0077ff;
        display: flex;
        justify-content: center;
        .editBtn {
          margin-right: 20px;
          cursor: pointer;
        }
        .delBtn {
          color: red;
        }
      }
    }
  }
  .sideBar {
    background: #ffffff;
    box-shadow: -3px 3px 6px 1px rgba(59, 60, 61, 0.1);
    border-radius: 4px 4px 4px 4px;
    padding: 20px 6px;
    position: fixed;
    right: 24px;
    top: 112px;
    font-size: 16px;
    .sideBarItem {
      width: 60px;
      padding: 13px 3px 0;
      text-align: center;
      cursor: pointer;
      .bottomTia {
        width: 40px;
        height: 2px;
        background: #dbdfe5;
        margin: 8px auto;
      }
    }
    .active {
      color: #0077ff;
      background: linear-gradient(180deg, #ffffff 0%, #eff5ff 100%);
      .bottomTia {
        width: 40px;
        height: 2px;
        background: #0077ff;
      }
    }
  }
}
</style>
